const mongoose = require('mongoose');
const COLLECTIONS = require('./collections');

// 购物车商品项模式
const CartItemSchema = new mongoose.Schema({
  product: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Product',
    required: true
  },
  quantity: {
    type: Number,
    required: true,
    min: 1,
    default: 1
  },
  // 选择的规格（如颜色、尺寸等）
  selectedSpecs: {
    type: Map,
    of: String,
    default: new Map()
  },
  // 添加到购物车时的价格（防止价格变动影响购物车）
  priceAtAdd: {
    type: Number,
    required: true
  },
  // 添加时间
  addedAt: {
    type: Date,
    default: Date.now
  }
});

// 购物车模式
const CartSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    unique: true // 每个用户只有一个购物车
  },
  items: [CartItemSchema],
  // 购物车总金额（计算字段）
  totalAmount: {
    type: Number,
    default: 0
  },
  // 购物车总商品数量（计算字段）
  totalItems: {
    type: Number,
    default: 0
  },
  // 最后更新时间
  lastUpdated: {
    type: Date,
    default: Date.now
  }
}, {
  timestamps: true
});

// 在保存前计算总金额和总数量
CartSchema.pre('save', function(next) {
  this.totalItems = this.items.reduce((total, item) => total + item.quantity, 0);
  this.totalAmount = this.items.reduce((total, item) => total + (item.priceAtAdd * item.quantity), 0);
  this.lastUpdated = new Date();
  next();
});

// 添加方法：添加商品到购物车
CartSchema.methods.addItem = function(productId, quantity, selectedSpecs, price) {
  // 检查是否已存在相同商品和规格的项
  const existingItemIndex = this.items.findIndex(item => 
    item.product.toString() === productId.toString() && 
    JSON.stringify(Object.fromEntries(item.selectedSpecs)) === JSON.stringify(selectedSpecs)
  );

  if (existingItemIndex > -1) {
    // 如果存在，增加数量
    this.items[existingItemIndex].quantity += quantity;
  } else {
    // 如果不存在，添加新项
    this.items.push({
      product: productId,
      quantity,
      selectedSpecs: new Map(Object.entries(selectedSpecs || {})),
      priceAtAdd: price
    });
  }

  return this.save();
};

// 添加方法：更新商品数量
CartSchema.methods.updateItemQuantity = function(itemId, quantity) {
  const item = this.items.id(itemId);
  if (item) {
    if (quantity <= 0) {
      this.items.pull(itemId);
    } else {
      item.quantity = quantity;
    }
  }
  return this.save();
};

// 添加方法：移除商品
CartSchema.methods.removeItem = function(itemId) {
  this.items.pull(itemId);
  return this.save();
};

// 添加方法：清空购物车
CartSchema.methods.clearCart = function() {
  this.items = [];
  return this.save();
};

// 添加静态方法：获取用户购物车
CartSchema.statics.getByUserId = function(userId) {
  return this.findOne({ user: userId }).populate({
    path: 'items.product',
    select: 'name price mainImage images brand category countInStock'
  });
};

const Cart = mongoose.model('Cart', CartSchema, COLLECTIONS.CARTS);

module.exports = Cart;
